﻿using System;
using System.Net;
using System.Threading.Tasks;

namespace MiniAspNetCore
{
    /// <summary>
    /// 基于httplistener的服务器
    /// </summary>
    public class HttpListenerServer : IServer
    {
        private readonly string _url;
        private readonly HttpListener _listener = new HttpListener();

        public HttpListenerServer(string url)
        {
            _url = url;
        }

        /// <summary>
        /// 启动服务
        /// </summary>
        /// <returns></returns>
        public async Task StartAsync(RequestDelegate handler)
        {
            _listener.Prefixes.Add(_url ?? "http://localhost:5000/");

            Console.WriteLine("Server starting.....");
            _listener.Start();
            Console.WriteLine($"Server started in {_url}");

            await Listen(handler);
        }

        /// <summary>
        /// 监听请求
        /// </summary>
        /// <param name="handler"></param>
        /// <returns></returns>
        private async Task Listen(RequestDelegate handler)
        {
            try
            {
                while (true)
                {
                    Console.WriteLine("Server listening.....");

                    var context = await _listener.GetContextAsync();

                    var feature = new HttpListenerFeature(context);
                    var features = new FeatureCollection()
                        .Set<IHttpRequestFeature>(feature)
                        .Set<IHttpResponseFeature>(feature);
                    var httpContext = new HttpContext(features);

                    await handler(httpContext);
                    context.Response.Close();
                }
            }
            catch (Exception)
            {
                //ignore exception
            }
            finally
            {
                Console.WriteLine($"Server shutdown!");
                _listener.Close();
            }
        }
    }
}
